package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtPrps;


    /**
     * 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            HttpServletRequest request,
            HttpServletResponse response){

        String token = this.authService.accredit(username,password);

        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }

        //TODO 要把token 存入cookie

        if (null!=token){//写入cookie中
            CookieUtils.setCookie(request,response,jwtPrps.getCookieName(),token,jwtPrps.getCookieMaxAge(),null,true);
        }

        return ResponseEntity.ok().build();
    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN")String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response){//token刷新的业务

        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtPrps.getPublicKey());
            //重新生成token
            String newToken = JwtUtils.generateToken(userInfo, jwtPrps.getPrivateKey(), jwtPrps.getExpire());

            CookieUtils.setCookie(request,response,jwtPrps.getCookieName(),
                    newToken,jwtPrps.getCookieMaxAge(),null,true);

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
